<template>
  <div class="mark-config">
    <p class="tip">{{$t('configLazyLoad.intelligentQualityCheck.markTip1')}}</p>
    <el-row :gutter="60">
      <el-col :span="4" style="text-align: right;font-size:14px;font-weight:bolder;">{{$t('configLazyLoad.intelligentQualityCheck.baseConfig')}}</el-col>
      <el-col :span="20">
        <el-row class="item-line">
          <el-col :span="3">{{$t('configLazyLoad.intelligentQualityCheck.baseScore')}}：</el-col>
          <el-col :span="21"><el-input class="mark_input" type="number" v-model="baseForm.baseScore"></el-input></el-col>
        </el-row>
        <el-row class="item-line">
          <el-col :span="3">{{$t('configLazyLoad.intelligentQualityCheck.scoreConfig')}}：</el-col>
          <el-col :span="21">
            <el-input class="mark_input" placeholder="0" :disabled="true"></el-input><span class="mark_solid"><div>{{$t('qualityCheck.unqualified')}}</div></span>
            <el-input class="mark_input" type="number" v-model="baseForm.qualified"></el-input><span class="mark_solid"><div>{{$t('qualityCheck.qualified')}}</div></span>
            <el-input class="mark_input" type="number" v-model="baseForm.good"></el-input><span class="mark_solid"><div>{{$t('qualityCheck.excellent')}}</div></span>
            <el-input class="mark_input" placeholder="100" :disabled="true"></el-input>
          </el-col>
        </el-row>
        <el-row class="item-line">
          <el-col :span="3">{{$t('configLazyLoad.intelligentQualityCheck.adminAttention')}}：</el-col>
          <el-col :span="21">
            <el-checkbox style="float:left;" v-model="baseForm.isNotify">{{$t('configLazyLoad.intelligentQualityCheck.markTip2')}}</el-checkbox>
            <el-popover
              ref="agentPop"
              placement="bottom"
              @show="popoverShow"
              width="240"
              trigger="click">
              <agent-tree :readSeat="folllowedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
            </el-popover>
            <div class="follow-agent-wrap" v-popover:agentPop>
                        <span class="follow-agent follow-common" v-for="item in folllowedAgents" :key="item._id">{{item.label}}
                          <i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)"></i>
                        </span>
              <div>
                <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <div class="sub">
      <el-button type="primary" class="primary_btn fr ml10" @click="saveBaseScore">{{$t('public.save')}}</el-button>
      <el-button class="primary_btn fr" style="margin-right: 20px;" @click="resetBaseScore">{{$t('public.reset')}}</el-button>
    </div>
    <div style="border-bottom: 1px dashed #ccc;margin: 20px 0"></div>
    <el-row :gutter="60">
      <el-col :span="4" style="text-align: right;font-size:14px;font-weight:bolder;">{{$t('configLazyLoad.intelligentQualityCheck.markConfig')}}</el-col>
      <el-col :span="20" style="padding-bottom: 80px;">
        <el-row>
          <el-col :span="8" style="font-weight: bolder;padding-bottom: 20px;border-bottom: 1px solid #ccc;">{{$t('configLazyLoad.intelligentQualityCheck.parentItem')}}</el-col>
          <el-col :span="16" style="font-weight: bolder;padding-bottom: 20px;border-bottom: 1px solid #ccc;">{{$t('configLazyLoad.intelligentQualityCheck.childItem')}}</el-col>
        </el-row>
        <el-row class="mark_set_item" v-for="(item, index) in scoreConfig">
          <el-col :span="8" class="mark_set_item_par">
            <!--父项  编辑删除-->
            <div v-show="!item.editState"><span style="padding: 4px 8px">{{item.name}}</span><i @click="item.editState = true" class="el-icon-edit" style="margin:0 4px;"></i>&nbsp;<i class="el-icon-close mark_set_item_par_del" @click="edlParentsBtn(index)"></i></div>
            <!--父项保存-->
            <div v-show="item.editState"><el-input size="mini" :placeholder="$t('public.pleaseEnter')" :maxlength="10" v-model.trim="item.name" style="width:60%;margin-right:14px;"></el-input><i class="el-icon-check" @click="addParentsItem(index)"></i></div>
          </el-col>
          <el-col :span="16">
            <div class="mark_set_item_sub_item" v-for="(one, num) in item.subs">
              <span>{{one.name}}</span>
              <span>{{one.score}}</span>
              <i class="el-icon-error" @click="delMarkSub(index, num)"></i>
            </div>
            <div v-show="item._id" class="mark_set_item_sub_item" style="cursor: pointer;" @click="addMarkSubBtn(index)"><i class="el-icon-plus"></i> {{$t('configLazyLoad.intelligentQualityCheck.addChildItem')}}</div>
          </el-col>
        </el-row>
        <el-row class="mark_set_item">
          <div class="mark_set_item_sub_item" style="cursor: pointer;" @click="addParentsBtn"><i class="el-icon-plus"></i> {{$t('configLazyLoad.intelligentQualityCheck.addParentItem')}}</div>
        </el-row>
      </el-col>
    </el-row>
    <!--添加评分子项  弹窗=============================-->
    <el-dialog
      :title="$t('configLazyLoad.intelligentQualityCheck.addChildItem')"
      :visible.sync="addMarkSubDialogVisible"
      width="50%"
      @close="addMarkSubDialogVisibleClose">
      <el-form ref="subForm" :model="subForm" :rules="rules" label-width="150px">
        <el-form-item :label="$t('configLazyLoad.intelligentQualityCheck.childItemName') + ':'" prop="name">
          <el-input v-model.trim="subForm.name" style="width:80%;"></el-input>
        </el-form-item>
        <el-form-item :label="$t('configLazyLoad.intelligentQualityCheck.scoreSet') + ':'">
          <el-select v-model="subForm.plusOrMinus" @change="changePlusOrMinus" :placeholder="$t('public.pleasePick')" style="width:100px;margin-right:20px;">
            <el-option :label="$t('configLazyLoad.intelligentQualityCheck.plusPoints')" value="plus"></el-option>
            <el-option :label="$t('configLazyLoad.intelligentQualityCheck.minusPoints')" value="minus"></el-option>
            <el-option :label="$t('configLazyLoad.intelligentQualityCheck.noSoring')" value="noSoring"></el-option>
          </el-select>
          <el-input v-model="subForm.subscore" v-show="subForm.plusOrMinus!='noSoring'" style="width: calc(80% - 120px);"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="addMarkSubDialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="addMarkSub">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {deepClone} from '@/utils/m7Utils.js'
  import AgentTree from '../../../qualityCheck/base/qualityAgentTree.vue'
  export default {
    name: 'MarkConfig',
    data () {
      return {
        curIndex: 0,
        addMarkSubDialogVisible: false,
        scoreConfig: [
          {name: this.$t('configLazyLoad.intelligentQualityCheck.curse'),
            editState: false,
            subs: [
            {name: 'fuck', score: -10},
            {name: this.$t('configLazyLoad.intelligentQualityCheck.idiot'), score: -5}]
          }
        ],
        baseForm: {
          baseScore: 90,
          qualified: 60,
          good: 80,
          isNotify: false,
          notifyAgents: []
        },
        subForm: {name: '', subscore: 1, plusOrMinus: 'plus'},
        rules: {
          name: [
            { required: true, message: this.$t('configLazyLoad.intelligentQualityCheck.enterChildItemName'), trigger: 'blur' }
          ]
        },
        DISPOSAL_AGENT: []
      }
    },
    methods: {
      getBaseScoreChche () {
        this.$store.dispatch('getBaseConfig', {}).then(res => {
          if (res.success) {
            if (res.data) {
              this.baseForm.baseScore = res.data.baseScore
              this.baseForm.qualified = res.data.qualified
              this.baseForm.good = res.data.good
              this.baseForm.isNotify = res.data.isNotify
              this.baseForm.notifyAgents = res.data.notifyAgents
              this.DISPOSAL_AGENT = res.data.notifyAgents
              this.$refs.agentTree.setCheckedKeys()
            }
          }
        })
      },
      getScoreConfig () {
        this.$store.dispatch('getScoreConfig', {}).then(res => {
          if (res.success) {
            if (res.data) {
              this.scoreConfig = res.data
              this.scoreConfig.forEach(item => {
                this.$set(item, 'editState', false)
              })
            }
          }
        })
      },
//        保存基础分值
      saveBaseScore () {
        this.baseForm.notifyAgents = this.DISPOSAL_AGENT
        console.log(this.baseForm)
        this.baseForm.baseScore = Number(this.baseForm.baseScore)
        this.baseForm.qualified = Number(this.baseForm.qualified)
        this.baseForm.good = Number(this.baseForm.good)
        let baseScoreFlag = Number.isInteger(this.baseForm.baseScore)
        let qualifiedFlag = Number.isInteger(this.baseForm.qualified)
        let goodFlag = Number.isInteger(this.baseForm.good)
        if (!baseScoreFlag || !qualifiedFlag || !goodFlag) {
          this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.markError1'))
          return
        }
        if (this.baseForm.baseScore < 0 || this.baseForm.baseScore > 100) {
          this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.markError2'))
          return
        }
        if (this.baseForm.qualified < 0 || this.baseForm.good > 100 || this.baseForm.qualified > this.baseForm.good) {
          this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.markError3'))
          return
        }
        this.$store.dispatch('updateBasicConfig', this.baseForm).then(res => {
          if (res.success) {
            this.$message.success(this.$t('config.channel.saveSuccess'))
          }
        })
      },
      resetBaseScore () {
        this.baseForm.baseScore = 90
        this.baseForm.qualified = 60
        this.baseForm.good = 80
        this.baseForm.isNotify = false
        this.baseForm.notifyAgents = []
        this.DISPOSAL_AGENT = []
        this.$refs.agentTree.setCheckedKeys()
      },
//        添加父项
      addParentsBtn () {
        let flag = true
        this.scoreConfig.forEach(item => {
          if (item.editState === true) {
            this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.markError4'))
            flag = false
            return false
          }
        })
        if (flag) {
          this.scoreConfig.push({name: '', editState: true, subs: []})
        }
      },
      addParentsItem (index) {
        if (!this.scoreConfig[index].name) {
          this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.markError5'))
          return false
        }
        if (this.scoreConfig[index]._id) {
          this.$store.dispatch('updateScoreConfig', {name: this.scoreConfig[index].name, _id: this.scoreConfig[index]._id}).then(res => {
            if (res.success) {
              this.$message.success(this.$t('business.updateSuccess'))
              this.scoreConfig[index].editState = false
              this.getScoreConfig()
            }
          })
        } else {
          this.$store.dispatch('addScoreConfig', {name: this.scoreConfig[index].name}).then(res => {
            if (res.success) {
              this.$message.success(this.$t('config.customer.addSucc'))
              this.scoreConfig[index].editState = false
              this.getScoreConfig()
            }
          })
        }
      },
//      删除父项
      edlParentsBtn (index) {
        this.$store.dispatch('removeScoreConfig', {_id: this.scoreConfig[index]._id}).then(res => {
          if (res.success) {
            this.$message.success(this.$t('config.channel.deleteSuccess'))
            this.scoreConfig.splice(index, 1)
          } else {
//            this.$message.error('使用中，删除失败')
          }
        })
      },
//      添加评分子项弹窗
      addMarkSubBtn (index) {
        this.curIndex = index
        this.addMarkSubDialogVisible = true
      },
      addMarkSub () {
        if (this.subForm.subscore === '' || Number(this.subForm.subscore) < 0 || Number(this.subForm.subscore) > 100) {
          this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.markError6'))
          return
        }
        this.$refs.subForm.validate((valid) => {
          if (valid) {
            let score = this.subForm.plusOrMinus === 'plus' ? Math.abs(Math.floor(this.subForm.subscore * 100) / 100) : -Math.abs(Math.floor(this.subForm.subscore * 100) / 100)
            let data = {
              parent: this.scoreConfig[this.curIndex]._id,
              name: this.subForm.name || '',
              score: score
            }
            this.$store.dispatch('addSubScoreConfig', data).then(res => {
              if (res.success) {
                this.scoreConfig[this.curIndex].subs.push({name: this.subForm.name, score: score})
                this.addMarkSubDialogVisible = false
                this.$message.success(this.$t('config.customer.addSucc'))
                this.getScoreConfig()
              }
            })
          } else {
            return false
          }
        })
      },
//      添加评分子项 弹窗关闭回掉===
      addMarkSubDialogVisibleClose () {
        this.subForm = {name: '', subscore: 1, plusOrMinus: 'plus'}
      },
      //      删除评分子项===
      delMarkSub (index, num) {
        let data = {
          parent: this.scoreConfig[index]._id,
          sub: this.scoreConfig[index].subs[num]._id
        }
        this.$store.dispatch('rmSubScoreConfig', data).then(res => {
          if (res.success) {
            this.scoreConfig[index].subs.splice(num, 1)
            this.$message.success(this.$t('config.channel.deleteSuccess'))
          } else {
//            this.$message.error('使用中，删除失败')
          }
        })
      },
      saveFollowedAgents (agents) {
        this.DISPOSAL_AGENT = deepClone(agents)
        document.getElementsByTagName('body')[0].click()
      },
      closeFollowedAgents (agent) {
        this.DISPOSAL_AGENT = this.DISPOSAL_AGENT.filter((item) => item !== agent)
      },
      popoverShow () {
        this.$refs.agentTree.setCheckedKeys()
      },
      //分值设置
      changePlusOrMinus(val){
        this.subForm.plusOrMinus = val;
        if(this.subForm.plusOrMinus=='noSoring'){
          this.subForm.subscore = 0
        }
      }
    },
    computed: {
      folllowedAgents () {
        let agents = this.DISPOSAL_AGENT || []
        let agentsAll = this.$store.getters.agents || {}
        let data = []
        agents.forEach(item => {
          if (agentsAll[item]) {
            data.push({_id: item, label: agentsAll[item].displayName})
          }
        })
        return data
      }
    },
    components: {
      AgentTree
    },
    beforeMount () {
      this.getScoreConfig()
      this.getBaseScoreChche()
    },
    activated () {
      this.getScoreConfig()
      this.getBaseScoreChche()
    }
  }
</script>
<style lang="stylus" scope>
  @import "../../../../../assets/common.styl"
  import
  .mark-config
    padding 0px 20px
    height calc(100vh - 125px)
    width calc(100%)
    box-sizing border-box
    overflow-y auto
    overflow-x hidden
    .tip
      padding 14px 0
      color #666
      border-bottom 1px solid #ccc
      margin-bottom 20px
    .item-line
      margin-bottom 20px
    .mark_input
      width 90px
    .mark_solid
      display inline-block
      position relative
      top -8px
      padding 0px 8px
      div
        border-bottom 2px solid #ccc
    .sub
      overflow hidden
    .mark_set_item
      padding 20px 0px
      border-bottom 1px solid #ccc
      .mark_set_item_sub_item
        padding 4px
        margin 0 20px 10px 0
        display inline-block
        border 1px solid #ccc
        border-radius 3px
        position relative
        .el-icon-error
          color red
          cursor pointer
          position absolute
          right -5px
          top -5px
        span
          padding 0 6px
        span:nth-child(1)
          border-right 1px solid #ccc
      .mark_set_item_par
        div
          i
            font-size 14px
            color $c-main
            cursor pointer
          .mark_set_item_par_del
            color red
    .follow-label
      line-height 24px
      font-size 12px
    .follow-agent-wrap
      display inline-block
      cursor pointer
      width: 270px
      border-radius: 5px
      border: 1px solid #dcdfe6
      padding: 6px 9px 6px 5px
      margin-left: 20px
      overflow: hidden
    .follow-common
      float left
      position relative
      line-height 24px
      background-color #7ab8f3
      margin 0 0 10px 10px
      padding 0 10px
      color #fff
      border-radius 4px
    .follow-agent-add
      cursor pointer
    .el-icon-close
      font-size 12px
    .follow-agent
      &:hover
        .el-icon-close
          display block
      .el-icon-close
        display none
        position absolute
        right -10px
        top -10px
        width 24px
        height 24px
        font-size 12px
        line-height 24px
        transform scale(0.6)
        text-align center
        color #fff
        background-color #0f99fc
        border-radius 50%
        border 1px solid #cce6ff
        cursor pointer
    .follow-agent-wrap-btn
      display block !important
      line-height 0px
      float right
      cursor pointer
      color $c-main
      overflow: hidden
</style>
